import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { type CallToolResult, type GetPromptResult } from '@modelcontextprotocol/sdk/types';
import { z } from 'zod';
import { captureSwaggerDataFromUrl } from './data-capture';
import { Logger } from '~/utils/logger';
import {
  SwaggerResource,
  swaggerResourceTemplate,
  swaggerResourceUriPrefix,
  transientSwaggerResourceStore,
} from './resource';

let mcpServer: McpServer = null;

const SwaggerDataToolName = 'get_swagger_specs_and_create_resource';

const toolInputSchema = z.object({
  // https://swagger.mucang.cn/v3/index.html?url=https://volvo-coach.ttt.mucang.cn/__/swagger/view.htm
  swaggerUrl: z
    .string()
    .describe('Swagger文档的完整URL地址，例如：https://swagger.mucang.cn/v3/index.html?url=...'),
});

const promptInputSchema = z.object({
  swaggerUrl: z.string().describe('Swagger文档的完整URL地址'),
  language: z.string().default('TypeScript').describe('生成代码的语言，默认为TypeScript'),
  framework: z.string().default('axios').describe('HTTP客户端框架，默认为axios'),
});

/** 从Swagger URL中解析标识符 */
function parseSwaggerIdentifier(url: string): { host: string; path: string } {
  try {
    const urlObj = new URL(url);
    const params = new URLSearchParams(urlObj.search);
    const apiUrl = params.get('url');

    if (apiUrl) {
      const apiUrlObj = new URL(apiUrl);
      return {
        host: apiUrlObj.hostname.replace(/\./g, '-'),
        path: apiUrlObj.pathname.replace(/[^a-zA-Z0-9]/g, '-'),
      };
    }

    return {
      host: urlObj.hostname.replace(/\./g, '-'),
      path: urlObj.pathname.replace(/[^a-zA-Z0-9]/g, '-'),
    };
  } catch (error) {
    Logger.warn(`解析Swagger标识符失败: ${error}`);
    return {
      host: 'unknown',
      path: 'api',
    };
  }
}

/** Swagger代码生成提示词处理器 */
async function swaggerPromptHandler(params: { swaggerUrl: string }): Promise<GetPromptResult> {
  Logger.info(`[Prompt] 启动Swagger代码生成, URL: ${params.swaggerUrl}`);

  return {
    messages: [
      {
        role: 'assistant',
        content: {
          type: 'text',
          text: swaggerToCodePrompt(),
        },
      },
      {
        role: 'user',
        content: {
          type: 'text',
          text: `使用 ${SwaggerDataToolName} 工具读取 ${params.swaggerUrl} 获取Swagger结构化数据，并结合项目规范和现有代码，对接接口字段和调用流程。`,
        },
      },
    ],
  };
}

async function handleGetSwaggerResource(params: { swaggerUrl: string }): Promise<CallToolResult> {
  try {
    Logger.info(`[Tool] 开始解析Swagger文档: ${params.swaggerUrl}`);

    const swaggerData = await captureSwaggerDataFromUrl(params.swaggerUrl);
    const { host, path } = parseSwaggerIdentifier(params.swaggerUrl);
    const resourceUri = `${swaggerResourceUriPrefix}${host}-${path}`.toLowerCase();

    // 创建资源记录
    const record: SwaggerResource = {
      uri: resourceUri,
      name: `Swagger API文档 - ${swaggerData.info?.title || '未知API'}`,
      description: `来自 ${params.swaggerUrl} 的Swagger API文档，包含所有接口定义、参数、响应等信息`,
      mimeType: 'application/json',
      text: JSON.stringify(swaggerData, null, 2),
    };

    // 存储到临时资源存储
    transientSwaggerResourceStore.set(resourceUri, record);

    const isConnected = mcpServer.isConnected();

    if (isConnected) {
      // 通知资源列表已更新
      mcpServer.sendResourceListChanged();

      // 注册动态资源
      mcpServer.resource('swagger-resource-template', resourceUri, function () {
        return {
          uri: record.uri,
          mimeType: record.mimeType,
          blob: record.blob,
        };
      });
    }

    Logger.info(`[Tool] 已创建Swagger资源: ${resourceUri}`);

    return {
      content: [
        {
          type: 'resource',
          description: `Swagger API文档已成功解析并存储为resource`,
          uri: resourceUri,
          resource: record,
        },
      ],
      isError: false,
    };
  } catch (error) {
    Logger.error(`[Tool] 解析Swagger文档失败: ${error}`);
    return {
      content: [
        {
          type: 'text',
          text: `❌ 解析Swagger文档失败：${error instanceof Error ? error.message : '未知错误'}`,
        },
      ],
      isError: true,
    };
  }
}

export function registerSwaggerDataTool(server: McpServer): void {
  mcpServer = server;

  server.registerPrompt(
    'generate-code-from-swagger',
    {
      title: '智能Swagger代码生成',
      description:
        '基于Swagger API文档URL，使用专业提示词指导，生成高质量、类型安全的API客户端代码',
      argsSchema: promptInputSchema.shape,
    },
    swaggerPromptHandler
  );

  server.registerTool(
    SwaggerDataToolName,
    {
      title: '获取Swagger API文档数据并创建资源',
      description: `解析Swagger文档URL，提取API定义数据，并创建包含完整API信息的临时资源。AI助手需要读取返回的resource来获取具体的API文档数据。`,
      inputSchema: toolInputSchema.shape,
    },
    handleGetSwaggerResource
  );

  // 注册资源模板 - 用于动态资源
  server.registerResource(
    'swagger-resource-template',
    swaggerResourceTemplate,
    {
      name: 'Swagger API文档资源',
      description: '从Swagger文档提取的API结构化数据资源',
      mimeType: 'application/json',
    },
    async (uri: URL) => {
      const uriString = uri.toString();
      Logger.info(`[Resource Template] 读取Swagger资源: ${uriString}`);

      // 从临时存储中获取资源
      const resource = transientSwaggerResourceStore.get(uriString);

      if (!resource) {
        Logger.error(`[Resource] Swagger资源未找到: ${uriString}`);
        throw new Error(`Swagger resource not found: ${uriString}`);
      }

      Logger.info(`[Resource] 成功读取Swagger资源: ${uriString}`);

      return {
        contents: [
          {
            uri: resource.uri,
            mimeType: resource.mimeType,
            text: resource.text,
          },
        ],
      };
    }
  );
}
